export default {
  install,
  hashCode,
  random,
  randomId,
  type,
  isMobile,
  redirection,
  numFilter,
  timeTransform
}

function install(Vue) {
  Vue.prototype.$u = {
    hashCode,
    random,
    randomId,
    type,
    isMobile,
    redirection,
    numFilter,
    isEmail,
    timeTransform
  }
}

function randomId(name) {
  return hashCode(name + random)
}

function hashCode(string) {
  let hash = 0
  let i
  let chr
  if (string.length === 0) return hash
  for (i = 0; i < string.length; i++) {
    chr = string.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0 // Convert to 32bit integer
  }
  return hash
}

function random(Min, Max) {
  let max = Max || 99999
  let min = Min || 10000
  let Range = max - min
  let Rand = Math.random()
  return (min + Math.round(Rand * Range))
}

function type(item) {
  return Object.prototype.toString.call(item).replace('[object ', '').replace(']', '')
}

function isMobile() {
  // return (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))
  return !(navigator.userAgent.toLowerCase().includes('window' || 'mac'))
}

function redirection(str) {
  let parent = ''
  if (window.name == '') {
    parent = window.location.href.substr(0, window.location.href.lastIndexOf('/') + 1)
    window.name = 'choice'
  }
  if (str.includes('http') || str.includes('www')) {
    window.location.href = str
  } else {
    window.location.href = parent + str
  }
}

function numFilter(num) {
  let t = '' + num
  if (num > 1000 && num < 10000) {
    return t[0] + '千'
  } else {
    if (num >= 10000) {
      return t.substr(0, t.length - 3) + '万'
    } else {
      return num
    }
  }
}

function isEmail(email) {
  const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
  return reg.test(email)
}

function timeTransform(str) {
  return new Date(str + 8 * 3600 * 1000).toJSON().substr(0, 19).replace('T', ' ')
}
